package com.xxrl.hmwork.service;

import com.xxrl.hmwork.conf.MyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Calendar;
import java.util.Random;

/**
 * @author mis
 */
@Service
public class StatisticsService {
    private final MyConfig myConfig;

    /**
     * visit 一周的访问记录, 分管理员和普通用户
     * totalVisit 总访问量
     * totalHomework 总作业数
     */
    public Long[][] visit;
    public Long totalVisit;
    public Long totalHomework;
    public Long totalUser;
    public Long totalFiles;
    private Integer dayOfTheWeek;
    @Autowired
    public StatisticsService(MyConfig myConfig) {
        this.myConfig = myConfig;
        Random random = new Random();
        visit = new Long[2][7];
        totalHomework = 0L;
        // userController list 方法被调用时被赋值
        totalUser = 3L;
        totalVisit = 0L;
        totalFiles = getFileCount(new File(myConfig.getCloudDir())) + getFileCount(new File(myConfig.getUploadDir()));
        // 换算成 0~6
        dayOfTheWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1;
        // 开发环境 给点假数据
        if ("dev".equals(myConfig.getEnv())) {
            for (int i = 0; i < 7 ;++i) {
                visit[0][i] = Math.abs(random.nextLong()%100);
                visit[1][i] = Math.abs(random.nextLong()%100);
            }
        } else {
            for (int i = 0; i < 7 ; ++i) {
                visit[1][i] = 0L;
                visit[0][i] = 0L;
            }
        }
    }

    private Long getFileCount(File file) {
        if (!file.exists()) {
            return 0L;
        }
        Long ret = 1L;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File child : files) {
                    ret += getFileCount(child);
                }
            }
        }
        return ret;
    }

    public void visit(int type) {
        visit[type][dayOfTheWeek]++;
        totalVisit++;
    }

    @Scheduled(cron = "0 0 0 * * ? ")
    public void update() {
        dayOfTheWeek = (dayOfTheWeek+1)%7;
        visit[0][dayOfTheWeek] = 0L;
        visit[1][dayOfTheWeek] = 0L;
        // 重新统计文件
        totalFiles = getFileCount(new File(myConfig.getCloudDir())) + getFileCount(new File(myConfig.getUploadDir()));
    }
}
